<?php
/**
 * @var \Pinenut\Action $this
 */

$emptyValue = false;
if ($params['multiple']) {
	if (empty($value) || (0 == $value)) {
		$emptyValue = true;
	}
} else {
	if ((empty($value) || (0 == $value)) && (empty(reset($params['options'])))) {
		$emptyValue = true;
	}
}
?>
<?php $this->registerResourcePackage('bootstrapSelect');?>

<?php $this->inlineBlockBegin('js', \Resources\Layout\Postprocessing::POSITION_JS_CODE); ?>
	<script>
		$(function(){
			window.initSelectPicker();
		});
	</script>

<?php $this->inlineBlockEnd(); ?>
<?php $visibleValue = null; ?>
<div class="form-group">
	<label class="col-sm-3 control-label"><?php echo $params['label']; ?></label>
	<div class="col-sm-7">
		<div class="select-wrapper <?php if ($emptyValue) { echo 'empty-value'; } ?>"
			data-errors="<?php echo json_encode($errors)?>">
			<select class="selectpicker hidden-select"
			<?php echo $params['multiple']?'multiple':''?>
			title="<?php if (!empty($params['noneSelectedText'])) echo $params['noneSelectedText']; ?>"
			data-container="body"
			<?php echo $this->prepareAttr($params['htmlOptions']) ?>
			name="<?=$name . ($params['multiple']?'[]':'')?>">
			<?php foreach($params['options'] as $optionName => $optionValue)
				if (!($params['multiple'] && null === $optionValue)) { ?>
					<option <?php if ((string)$value === (string)$optionName || (is_array($value) && in_array($optionName, $value))) {
						echo 'selected';
						$visibleValue = $optionValue;
					} ?>
					value="<?php echo $this->txt2attr($optionName) ?>">
						<?php echo $this->txt2html($optionValue); ?>
					</option>
				<?php } ?>
			</select>

			<div class="btn-group bootstrap-select selectpicker-bootafor"
				 <?php if ($params['htmlOptions']['data-width']) { ?>
					 style="width: <?php echo $params['htmlOptions']['data-width'] ?>"
				 <?php } ?>
				 >
				<button data-toggle="dropdown" class="btn dropdown-toggle selectpicker btn-default"
						type="button">
					<span class="filter-option pull-left"><?php
						if ($visibleValue) {
							echo $this->txt2html($visibleValue);
						} else if (!empty($params['noneSelectedText'])) {
							echo $params['noneSelectedText'];
						}?></span>&nbsp;<span class="caret"></span>
				</button>
			</div>
		</div>

		<div class="element-notice description"><?php echo $params['description']; ?></div>
		<div class="element-notice error"><?php echo implode(', ', $errors) ?></div>
	</div>
</div>
